<!--  -->
<template>
  <div v-if="isLogin">
    <el-page-header :icon="null" title="用户">
      <template #content>
        <div class="flex items-center">
          <el-avatar
            :size="32"
            class="mr-3"
            :src="user.picture"
          />
          <span class="text-large font-600 mr-3"> {{ user.username }} </span>
          <span
            class="text-sm mr-2"
            style="color: var(--el-text-color-regular); margin-left: 25px"
          >
            身份：
          </span>
          <el-tag>{{ user.isAdmin === "0" ?'Admin':'Defult' }}</el-tag>
        </div>
      </template>
      <template #extra>
        <div class="flex items-center">
          <el-button @click="logout">退出</el-button>
          <el-button type="primary" class="ml-2" @click="mine">主页</el-button>
          <!-- <el-button class="pb" @click="toArticleEdit"><el-icon><Plus /></el-icon>发布</el-button> -->

          <el-button text @click="dialogFormVisible = true,initialization()" class="pb">
            <el-icon><Plus /></el-icon>发布
          </el-button>

          <el-dialog v-model="dialogFormVisible" title="发布帖子">
            <el-form :model="form">
              <el-form-item label="帖子名称" :label-width="formLabelWidth">
                <el-input v-model="form.title" autocomplete="off" />
              </el-form-item>
              <!-- <el-form-item label="Zones" :label-width="formLabelWidth">
                <el-select v-model="form.region" placeholder="Please select a zone">
                  <el-option label="Zone No.1" value="shanghai" />
                  <el-option label="Zone No.2" value="beijing" />
                </el-select>
              </el-form-item> -->
              <el-form-item label="封面" :label-width="formLabelWidth">
                <el-upload action="" :http-request="upload" :on-success="successUpload">
                  <el-button size="small" type="primary">点击上传</el-button>
                </el-upload>
              </el-form-item>
              <el-form-item label="简介" :label-width="formLabelWidth">
                <el-input v-model="form.description" autocomplete="off" />
              </el-form-item>
              <el-form-item label="可选标签" :label-width="formLabelWidth">
                <el-select
                  v-model="form.tags"
                  multiple
                  collapse-tags
                  placeholder="Select"
                  style="width: 240px"
                >
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="编写文章" :label-width="formLabelWidth">
                <div id="editor" style="width: 100%;">

                </div>
              </el-form-item>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="dialogFormVisible = false,publish()">
                  发布
                </el-button>
              </span>
            </template>
          </el-dialog>


        </div>
      </template>
    </el-page-header>
  </div>
  <div v-else>
    <el-page-header :icon="null" title="用户尚未登陆">
        <template #content>
            
        </template>
        <template #extra>
        <div class="flex items-center">
          <el-button type="success" class="ml-2" @click="login">登录</el-button>
        </div>
      </template>
    </el-page-header>
  </div>
</template>

<script>
import E from "wangeditor"
import axios from "axios"
import { ElMessage } from 'element-plus'
import { ElNotification } from 'element-plus'

let editor 
function initWangEditor(content){setTimeout(()=>{
  if(!editor){
    editor= new E("#editor")
    editor.config.placeholder="请输入内容"
    editor.config.uploadFileName='file'
    editor.config.uploadImgAccept = []
    editor.config.uploadImgServer = 'http://localhost:8888/files/wang/upload'
    editor.create()
  }
  editor.txt.html(content)
},0)
}
import { computed } from "vue";
export default {
  name: "Nav",
  components: {},
  props: {},
  data() {
    return {
        user:this.$store.state.user,
        isLogin:computed(()=>{
          if (typeof this.user !== 'object' || JSON.stringify(this.user) === '{}') {
            console.log('未登录');
            return false;
          }
          console.log('登录'+JSON.stringify(this.user));
          return true;
        }),
        form:{
          title: '123123',
          description: '',
          tags:[],
          content:'',
          cover:''
        },
        dialogTableVisible: false,
        dialogFormVisible : false,
        formLabelWidth : '140px',
        options : this.$store.state.tags
    };
  },
  computed: {},
  watch: {},
  methods: {
    initialization(){
      this.form={}
      initWangEditor("")
    },
    publish(){    //存入后端
      // if (this.form.title === '' || this.form.title === undefined) {
      //   ElMessage.error('标题不能为空.')
      //   return
      // }
      // if (this.form.description === '' || this.form.description === undefined) {
      //   ElMessage.error('简介不能为空.')
      //   return
      // }
      // if (this.form.content === '' || this.form.content === undefined) {
      //   ElMessage.error('内容不能为空.')
      //   return
      // }
      // if (this.form.cover === '' || this.form.cover === undefined) {
      //   ElMessage.error('封面不能为空.')
      //   return
      // }
      //author,author_gravatar, author_id, title, description,tags,content,cover
      this.form.author=this.user.username           /** author **/
      this.form.author_gravatar=this.user.picture   /** author_gravatar **/
      this.form.author_id=this.user.u_id            /** author_id **/
      this.form.title=this.form.title               /** title **/
      this.form.description=this.form.description   /** description **/
      if (this.form.tags.length > 0) {              /** tags **/
        this.form.tags = this.form.tags.join(',')   //转换为后端存入需要的字符串
      }else{
        this.form.tags = ''
      }
      this.form.content=editor.txt.html()           /** content **/
      this.form.cover=this.form.cover                /** cover **/
      this.form
      const url = 'http://localhost:8888/article/save'
      axios.post(url,JSON.parse(JSON.stringify(this.form)),{header:{'Content-Type': 'application/json'}}).then( data =>{
        ElMessage({
          message: '上传成功.',
          type: 'success',
        })
        ElNotification({
          title: '您的作品已经发布',
          message: "相关信息请在个人页面查看",
        })
        console.log(JSON.parse(JSON.stringify(this.form)));
        this.formInit()  // 重新初始化表单
      }).catch(Response=>{
        ElMessage.error('上传失败.')
      })
      console.log(JSON.stringify(this.form));
    },
    upload(param){  //上传封面
      const formData = new FormData();
      formData.append('file', param.file);
      const url = 'http://localhost:8888/cover/coverUpload'
      axios.post(url, formData).then( data =>{
        ElMessage({
          message: '上传成功.',
          type: 'success',
        })
        this.form.cover=data.data.data[0].url
        console.log(this.form.cover);
      }).catch(Response=>{
        ElMessage.error('上传失败.')
      })
    },
    formInit(){
      this.form ={
          author:'',
          author_id:'',
          title: '',
          description: '',
          tags:[],
          content:'',
          cover:''
      },
      this.dialogFormVisible = false,
      initWangEditor("")
    },
    login(){
      this.$router.push("/login")
    },
    logout(){
      this.$store.commit('logout')
      this.$router.push("/login")
    },
    mine(){
      this.$router.push({path:'/mine',query:{id:this.$store.state.user.u_id}})
    }
  },
  created() {
    console.log(this.$store.state.user);
  },
  mounted() {},
};
</script>

<style scoped>
.pb{
  border-radius: 20px;
  background-color: #fc5531 !important;
  color: #fff !important;
  border: none;
}
.pb:hover{
  background-color: #fff !important;
  color: #fc5531 !important;
}
</style>
